package com.jfinal.plugin.activerecord;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ParsedSql {
	static final Object[] EMPTY_PARA_ARRAY = new Object[0];
	private static final String NAMEED_REGEX = "(:[a-zA-Z0-9_]+)";
	public String sql;
	public Object[] paras;

	public String getSql() {
		return sql;
	}

	public Object[] getParas() {
		return paras;
	}

	private List<String> parameterNames = new ArrayList<String>();

	public ParsedSql() {
	}

	public ParsedSql(String namedSql, Map<String, Object> paraMap) {
		parseSql(namedSql);
		buildValueArray(paraMap);
	}

	public void parseSql(String namedSql) {
		Pattern p = Pattern.compile(NAMEED_REGEX);
		Matcher m = p.matcher(namedSql);
		int count = m.groupCount();

		while (m.find()) {
			for (int i = 0; i < count; i++) {
				parameterNames.add(m.group(i).substring(1));
			}
		}
		this.sql = namedSql.replaceAll(NAMEED_REGEX, "?");
	}

	/**
	 * @Title: build 参数值
	 * @param parsedSql
	 * @param paraMap
	 * @return
	 */
	public void buildValueArray(Map<String, Object> paraMap) {
		if (paraMap == null || paraMap.size() == 0) {
			this.paras = EMPTY_PARA_ARRAY;
			return;
		}

		int length = parameterNames.size();
		Object[] paras = new Object[length];

		for (int i = 0; i < length; i++) {
			String name = parameterNames.get(i);
			paras[i] = paraMap.get(name);
		}
		this.paras = paras;
	}

	/**
	 * @Title: 解析 sql 语句
	 * @param sqlBean
	 * @return
	 */
	public static final ParsedSql parseNamedSqlStatement(String namedSql, Map<String, Object> paraMap) {
		return new ParsedSql(namedSql, paraMap);
	}
}
